/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evolve.webbot.portal;
import  java.util.Date;
import  java.util.Properties;
import  java.util.ArrayList;
import  java.text.SimpleDateFormat;
import  java.io.IOException;
import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.FileInputStream;
import  java.io.InputStream;
import  java.io.OutputStream;
import  org.apache.log4j.Logger;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import  com.gargoylesoftware.htmlunit.html.*;
import  javax.swing.JTextArea;
import  com.evolve.webbot.beans.WebBotBeans;
import  com.evolve.webbot.file.XlsFileCoppel;
import  com.evolve.webbot.file.CommonErrorFile;


/**
 * @author DarthAE
 */
public class Coppel 
{
   private String path;
   private JTextArea jtextArea;
   public static String WB_MAIN_DIR     = "evolve-webbot";
   public static String COPPEL_MAIN_DIR = "coppel-webbot";
   public static String COPPEL_PROP_DIR = "coppel-properties";
   public static String COPPEL_PROP_ARC = "CoppelPortal.properties";
   public static String COPPEL_FILE_DIR = "coppel-files";
   public static String COPPEL_ERROR_FILE = "coppel-error-";
   public static String COPPEL_ARC_EXT  = ".xls";
   
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
   
   static Logger log = Logger.getLogger( Coppel.class );   

   public Coppel(){}

   public Coppel(String path,JTextArea jtextArea)
   { 
       this.path = path;
       this.jtextArea=jtextArea;
   }

   public WebClient creaWebClient()
   {
       WebClient webClient = null;

       webClient = new WebClient();
       webClient.setJavaScriptEnabled(true);
       webClient.setThrowExceptionOnScriptError(false);
       webClient.setAjaxController(new NicelyResynchronizingAjaxController());
       
       try{
            webClient.setUseInsecureSSL(true);
          }catch(Exception e){System.out.println(e);}
       

       return webClient;
   }

   public WebClient accesoPortal(WebClient webClient,
                                 WebBotBeans webBotBean)
   {
      int indPortalEjec       = 0;
      String errorFilePath    = "";
      String   xlsFilePath = null;
      ArrayList<String> listaCoppel = new ArrayList<String>();
      this.jtextArea.append("\nrecuperando archivo coppel");
      
      log.info("[-]descarga de informacion portal comercial coppel");
      
      CommonErrorFile   cef = new CommonErrorFile();
      
      Properties properties = new Properties();

      try{
          
           errorFilePath = this.path+File.separator+WB_MAIN_DIR+
                             File.separator+COPPEL_MAIN_DIR+
                             File.separator+COPPEL_FILE_DIR+
                             File.separator+COPPEL_ERROR_FILE+sdf.format(new Date())+".txt";
           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+COPPEL_MAIN_DIR+
                                                               File.separator+COPPEL_PROP_DIR+
                                                               File.separator+COPPEL_PROP_ARC);
           properties.load(fis);

           indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));           
           
           if(indPortalEjec==1)
           {
               try{
                    HtmlPage          pg1 = (HtmlPage)webClient.getPage(properties.getProperty("Coppel.UrlLogin"));
                    HtmlForm          fm1 = (HtmlForm)pg1.getByXPath("//form").get(0);
                    HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName(properties.getProperty("Coppel.UsrFormName"));
                    HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName(properties.getProperty("Coppel.PwdFormName"));

                    ti1.setValueAttribute(webBotBean.getUsuario());
                    pw1.setValueAttribute(webBotBean.getPassword());

                    HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName(properties.getProperty("Coppel.SmtFormName"));
                  
                    webClient.waitForBackgroundJavaScriptStartingBefore(10000);

                    try{
                         InputStream  is  = webClient.getPage(properties.getProperty("Coppel.UrlEstVenta")).getWebResponse().getContentAsStream();

                         Date fileDate = new Date();

                         SimpleDateFormat dateFotmat = new SimpleDateFormat("yyyyMMdd");
                         SimpleDateFormat timeFotmat = new SimpleDateFormat("HH-mm-ss");

                         xlsFilePath = this.path+File.separator+WB_MAIN_DIR+
                                                 File.separator+COPPEL_MAIN_DIR+
                                                 File.separator+COPPEL_FILE_DIR+
                                                 File.separator+properties.getProperty("Coppel.ArchivoPortal")+"-"+
                                                 dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+COPPEL_ARC_EXT;
                               
                        OutputStream out = new FileOutputStream(new File(xlsFilePath));

                        int read=0;
                        byte[] bytes = new byte[1024];

                        while((read = is.read(bytes))!= -1)
                        {out.write(bytes, 0, read);}

                        is.close();
                        out.flush();
                        out.close();
                       
                        this.jtextArea.append("\ndescarga de archivo terminada");
                        log.info("[-]descarga de informacion portal coppel terminada");
                     
                        this.jtextArea.append("\nGeneración de archivo de datos reporte");
                        log.info("[-]generacion de archivo de datos portal coppel");
                       
                         XlsFileCoppel xlsFile = new XlsFileCoppel(xlsFilePath);
                       
                         listaCoppel = xlsFile.getValuesFromXlsFile();
                         xlsFile.writeCoppelDataFile(xlsFile.getCoppelBeanValues(listaCoppel),fileDate);
                         this.jtextArea.append("\nArchivo de datos generado");
                         log.info("[-]archivo de datos portal coppel generado");

                         }catch(IOException ioe){ this.jtextArea.append("\nno se ha podido generar el archivo de datos"); 
                                                  cef.writeCommonWebTxtFile(errorFilePath,"no se ha podido generar el archivo de datos");
                                                  log.info("[-]error al generar archivo de datos portal coppel ",ioe);
                                                }

                  }catch(Exception e){this.jtextArea.append("\nerror al ingresar al portal");
                                      log.error("[-]error al navegar en portal coppel ",e);
                                      cef.writeCommonWebTxtFile(errorFilePath,"error al ingresar en portal coppel");
                                     }
           }
           else
           if(indPortalEjec == 0)
           {
             this.jtextArea.append("[-]Portal Coppel Desactivado");
             log.info("[-]Portal Coppel Desactivado");           
           }

         }catch(IOException ioe){System.out.println(ioe);
                                 log.error("[-]error al leer archivo de properties portal coppel ",ioe);
                                 cef.writeCommonWebTxtFile(errorFilePath,"error al leer archivo de properties portal coppel");
                                }

      return webClient;
   }

   public WebClient accesoPortal(WebClient webClient,String path,JTextArea jtextArea)
   {
      this.path = path;
      int indPortalEjec = 0;
      ArrayList<String> listaCoppel = new ArrayList<String>();
      String   xlsFilePath = null;
      
      System.out.println("\nrecuperando archivo coppel");
      jtextArea.append("\n[+]recuperando archivo coppel");
      
      Properties properties = new Properties();

      try{           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+COPPEL_MAIN_DIR+
                                                               File.separator+COPPEL_PROP_DIR+
                                                               File.separator+COPPEL_PROP_ARC);
           properties.load(fis);
           
           indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));
           
           if(indPortalEjec == 1)
           {
           try{
                HtmlPage          pg1 = (HtmlPage)webClient.getPage(properties.getProperty("Coppel.UrlLogin"));
                HtmlForm          fm1 = (HtmlForm)pg1.getByXPath("//form").get(0);
                HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName(properties.getProperty("Coppel.UsrFormName"));
                HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName(properties.getProperty("Coppel.PwdFormName"));

                ti1.setValueAttribute(properties.getProperty("Portal.user"));
                pw1.setValueAttribute(properties.getProperty("Portal.passwd"));
                
                System.out.println(properties.getProperty("Portal.user"));
                System.out.println(properties.getProperty("Portal.passwd"));

                HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName(properties.getProperty("Coppel.SmtFormName"));
                si1.click();

                //if(pg2!=null)
                //{
                  
                  webClient.waitForBackgroundJavaScriptStartingBefore(10000);

                  try{
                       InputStream  is  = webClient.getPage(properties.getProperty("Coppel.UrlEstVenta")).getWebResponse().getContentAsStream();

                       Date fileDate = new Date();

                       SimpleDateFormat dateFotmat = new SimpleDateFormat("yyyyMMdd");
                       SimpleDateFormat timeFotmat = new SimpleDateFormat("HH-mm-ss");

                       xlsFilePath = this.path+File.separator+WB_MAIN_DIR+
                                            File.separator+COPPEL_MAIN_DIR+
                                            File.separator+COPPEL_FILE_DIR+
                                            File.separator+properties.getProperty("Coppel.ArchivoPortal")+"-"+
                                            dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+COPPEL_ARC_EXT;
                       
                       File file = new File(xlsFilePath);
                       
                       OutputStream out = new FileOutputStream(file);

                       int read=0;
                       byte[] bytes = new byte[1024];

                       while((read = is.read(bytes))!= -1)
                       {
                           out.write(bytes, 0, read);
                       }

                       is.close();
                       out.flush();
                       out.close();
                       
                       System.out.println("\narchivo generado");
                       jtextArea.append("\narchivo generado");
                       
                       System.out.println("procesamiento de archivo "+xlsFilePath);
                       
                       jtextArea.append("\nprocesamiento de archivo "+xlsFilePath);
                       
                       XlsFileCoppel xlsFile = new XlsFileCoppel(xlsFilePath);
                       
                       listaCoppel = xlsFile.getValuesFromXlsFile();
                       xlsFile.writeCoppelDataFile(xlsFile.getCoppelBeanValues(listaCoppel),fileDate);
                       jtextArea.append("\narchivo separado por pipes generado");
                       
                     }catch(IOException ioe){ System.out.println("\nno se ha podido generar el archivo de datos"); 
                                              jtextArea.append("\nno se ha podido generar el archivo de datos");
                                             }

              }catch(Exception e){System.out.println(e);}           
          }
          else
          if(indPortalEjec == 0)
          {
             this.jtextArea.append("[-]Portal Coppel Desactivado");
             log.info("[-]Portal Coppel Desactivado");           
          }

         }catch(IOException ioe){System.out.println(ioe);}
      
      jtextArea.append("\n[+]fin descarga de archivos coppel");
      
      return webClient;
   }   
   
   public void terminaWebClient(WebClient webClient)
   {
       if(webClient!=null)
       {webClient.closeAllWindows();}
   }
}
